﻿#region 
/*---------------------------------------------------------------- 
* 项目名称 ：Mrc.Application.Middleware 
* 项目描述 ： 
* 类 名 称 ：FilterIPMidddleware 
* 类 描 述 ： 
* 所在的域 ：DESKTOP-HKKGEJ7
* 命名空间 ：Mrc.Application.Middleware
* 机器名称 ：DESKTOP-HKKGEJ7 
* CLR 版本 ：4.0.30319.42000 
* 作 者 ：mrc 
* 创建时间 ：2019/2/20 9:47:05 
* 更新时间 ：2019/2/20 9:47:05 
* 版 本 号 ：v1.0.0.0 
******************************************************************* 
* Copyright @ mrc 2019. All rights reserved. *******************************************************************
 //----------------------------------------------------------------*/
#endregion
using DotNetEx;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Memory;
using Mrc.Data;
using Mrc.Entity;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Mrc.Application.Middleware
{
    public class FilterIPMidddleware
    {
        private readonly RequestDelegate _next;
        public FilterIPMidddleware(RequestDelegate next)
        {
            _next = next;
        }
        public Task Invoke(HttpContext context)
        {
            
            if (CacheHelper.memoryCache==null)
            {
                CacheHelper.memoryCache = context.RequestServices.GetService(typeof(IMemoryCache)) as IMemoryCache;
            }
            reloadFilterIP(context);
            string ip=context.GetClientIP();
            if (GlobalsConfig.cacheType == "redis")
            {
                if (!RedisHelper.Exists("filterip"))
                {

                }
                RedisHelper.LPush("VisitIP", ip);
                if(RedisHelper.HashExists("filter:ip:",ip))
                {
                    context.Response.WriteAsync("无权限");
                }
            }
            else
            {            
                if (CacheHelper.memoryCache.Get<string>($"filter:ip:{ip}") != null)
                {
                    context.Response.WriteAsync("无权限");
                }               
            }
            return this._next(context);
        }

        private void reloadFilterIP(HttpContext context)
        {
            if (GlobalsConfig.cacheType == "redis")
            {
                if (!RedisHelper.Exists("filterip"))
                {
                   var IPs = (context.RequestServices.GetService(typeof(ISysFilterIPService)) as ISysFilterIPService).List(x=>x.IsEnable==true).Select(x=>x.StartIP).ToList();
                   var rds=RedisHelper.Instance;
                   rds.HashSet("filter:ip", IPs);
                   rds.Set("filterip","true");
                }
            }
            else
            { 
               if(CacheHelper.memoryCache.Get("filterip")==null)
               {
                    var IPs = (context.RequestServices.GetService(typeof(ISysFilterIPService)) as ISysFilterIPService).List(x => x.IsEnable == true).Select(x => x.StartIP).ToList();
                    IPs.ForEach((value) => {
                     CacheHelper.memoryCache.Set<string>($"filter:ip:{value}",value);
                    });
                    CacheHelper.memoryCache.Set<bool>("filterip",true);
               }
            }
        }
    }

    //请求中间件拓展
    public static partial class RequestMiddlewareExtensions
    {
        public static IApplicationBuilder UseFilterIP(
            this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<FilterIPMidddleware>();
        }
    }
    //public interface IFeatureCollection : IDictionary<Type, object> { }
    //public class FeatureCollection : Dictionary<Type, object>, IFeatureCollection { }
    //public static partial class Extensions
    //{
    //    public static T Get<T>(this IFeatureCollection features) => features.TryGetValue(typeof(T), out var value) ? (T)value : default(T);
    //    public static IFeatureCollection Set<T>(this IFeatureCollection features, T feature)
    //    {
    //        features[typeof(T)] = feature;
    //        return features;
    //    }
    //}

}
